import React, { Component } from 'react';
import {
  Button,
  Form,
  Input,
  Checkbox,
  Divider,
  Row,
  Col,
  message,
} from 'antd';
import { connect } from 'dva';
const CheckboxGroup = Checkbox.Group;
import PriviteList from './privite.json';

@connect(state => state['auth'])
export default class roleManageEdit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      authConfig: [],
      checkList: [],
      name: '',
      sort: '',
    };
  }
  componentWillMount() {
    this.getAuthConfig();
  }
  getAuthConfig = () => {
    this.props
      .dispatch({
        type: '$request/post',
        payload: {
          url: '/api/privilege/v1/queryPrivilegeGroup',
        },
      })
      .then(res => {
        this.setAuthConfit(res);
        this.getInitData();
      });
  };

  setAuthConfit = res => {
    PriviteList.forEach((privite, i) => {
      let tempPrivite = res[i];
      privite.privilegeList.forEach((list, j) => {
        let tempList = tempPrivite.privilegeList;
        list.forEach((item, q) => {
          let obj = tempList.find(t => t.code == item.code);
          list[q] = obj;
        });
      });
    });

    this.setState({
      authConfig: PriviteList,
    });
  };
  getInitData = () => {
    const name = this.props.location.state && this.props.location.state.name;
    if (!name) return;
    this.props
      .dispatch({
        type: '$request/post',
        payload: {
          url: '/api/privilege/v1/queryRole',
          data: { name, page: 0, size: 100 },
        },
      })
      .then(res => {
        const { dataList } = res;
        if (!dataList.length) return;
        const { privilegeVOList, name, sort } = dataList[0];
        const checkList = privilegeVOList.map(item => item.uuid);
        // this.formRef.current.setFieldsValue(res);
        this.setState({
          checkList,
        });
        this.formRef.current.setFieldsValue({ name, sort });
      });
  };
  onCheckAllChange = index => {
    const { authConfig, checkList } = this.state;
    authConfig[index].checkAll = !authConfig[index].checkAll;
    if (authConfig[index].checkAll) {
      authConfig[index].privilegeList.forEach(list => {
        list.forEach(item => {
          const has = checkList.findIndex(c => c == item.uuid);
          if (has < 0) checkList.push(item.uuid);
        });
      });
    } else {
      authConfig[index].privilegeList.forEach(list => {
        list.forEach(item => {
          const has = checkList.findIndex(c => c == item.uuid);
          if (has >= 0) checkList.splice(has, 1);
        });
      });
    }
    this.setState({
      authConfig,
      checkList,
    });
  };
  /**
   * 权限修改
   * @param {*} uuid
   */
  onChange = (uuid, index) => {
    let { checkList, authConfig } = this.state;
    const has = checkList.findIndex(item => item == uuid);
    if (has >= 0) {
      checkList.splice(has, 1);
    } else {
      checkList.push(uuid);
    }
    // 修改checkAll
    let checked = 0;
    let len = 0;
    authConfig[index].privilegeList.forEach(list => {
      list.forEach(item => {
        len += 1;
        const has = checkList.some(c => c == item.uuid);
        checked += has;
      });
    });
    if (checked == len) {
      authConfig[index].checkAll = true;
    } else {
      authConfig[index].checkAll = false;
    }
    this.setState({ checkList, authConfig });
  };
  cancel = () => {
    this.props.dispatch({
      type: '$router/back',
    });
  };
  onFinish = formData => {
    console.log(formData);
    const { checkList } = this.state;
    const uuid = this.props.location.state && this.props.location.state.id;
    const url = uuid
      ? '/api/privilege/v1/updateRole'
      : '/api/privilege/v1/createRole';
    this.props
      .dispatch({
        type: '$request/post',
        payload: {
          url: url, //'/api/privilege/v1/updateRole',
          data: { ...formData, privilegeUuidList: checkList, uuid },
        },
      })
      .then(res => {
        message.success(uuid ? '修改成功' : '添加成功');
        this.props.dispatch({ type: '$router/back' });
      });
  };
  formRef = React.createRef();
  render() {
    const { authConfig, initData, checkList } = this.state;
    return (
      <div>
        <Form ref={this.formRef} name="control-ref" onFinish={this.onFinish}>
          <Row>
            <Col span={5}>
              <Form.Item
                name="name"
                label="角色名称"
                rules={[{ required: true, message: '角色名称不能为空' }]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={5} offset={2}>
              <Form.Item name="sort" label="排序">
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <div>
            <p>权限配置</p>
            {authConfig.map((item, index) => {
              return (
                <div key={index}>
                  <div>
                    <Checkbox
                      onChange={() => this.onCheckAllChange(index)}
                      checked={item.checkAll}
                      style={{
                        paddingBottom: 10,
                        marginBottom: 10,
                        width: '100%',
                        fontSize: 18,
                      }}
                    >
                      {item.name}
                    </Checkbox>
                  </div>
                  {item.privilegeList.map((one, i) => (
                    <div key={i}>
                      {one.map((tow, k) => (
                        <Checkbox
                          checked={checkList.some(c => c == tow.uuid)}
                          disabled={tow.sys}
                          onClick={() => this.onChange(tow.uuid, index)}
                          key={k}
                          style={{ width: '150px' }}
                        >
                          {tow.name}
                        </Checkbox>
                      ))}
                    </div>
                  ))}
                  <Divider />
                </div>
              );
            })}
          </div>
          <Row>
            <Button htmlType="submit" type="primary">
              确定
            </Button>
            <Button style={{ marginLeft: 30 }} onClick={() => this.cancel()}>
              取消
            </Button>
          </Row>
        </Form>
      </div>
    );
  }
}
